import { Byte } from '../../api/io/Byte';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';



/**角色信息属性枚举*/
export const enum E_Role {
	/**玩家id*/
	PLAYER_ID = 0,
	/**服务器id*/
	SERVER_ID = 1,
	/**昵称*/
	NICKNAME = 2,
	/**枚举数量*/
	EnumCount = 3
}


/**角色信息*/
export class Role {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_ROLE_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_ROLE_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: Role[] = [];

	/**创建入口*/
	public static create(json?: string): Role {
		const c = this.POOL.pop() || new Role();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**玩家id (uint32)*/
	protected _playerId: number;
	/**服务器id (long)*/
	protected _serverId: number;
	/**昵称*/
	protected _nickname: string;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (Role.POOL.indexOf(this) === -1) {
			Role.POOL.push(this);
		}
	}

	/**玩家id*/
	public get playerId() {
		return this._playerId;
	}


	/**玩家id*/
	public set playerId(v: number) {
		this._playerId = v;
	}


	/**服务器id*/
	public get serverId() {
		return this._serverId;
	}


	/**服务器id*/
	public set serverId(v: number) {
		this._serverId = v;
	}


	/**昵称*/
	public get nickname() {
		return this._nickname;
	}


	/**昵称*/
	public set nickname(v: string) {
		this._nickname = v;
	}



	/**通过枚举获取值*/
	public getV(k: E_Role): any {
		switch (k) {
			case E_Role.PLAYER_ID: return this._playerId;
			case E_Role.SERVER_ID: return this._serverId;
			case E_Role.NICKNAME: return this._nickname;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_Role, v: any): void {
		switch (k) {
			case E_Role.PLAYER_ID: this._playerId = v; break;
			case E_Role.SERVER_ID: this._serverId = v; break;
			case E_Role.NICKNAME: this._nickname = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//玩家id
		this._playerId = 0;
		//服务器id
		this._serverId = 0;
		//昵称
		this._nickname = '';
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._playerId) {
			json.playerId = this._playerId;
		}
		if (this._serverId) {
			json.serverId = this._serverId;
		}
		if (this._nickname) {
			json.nickname = this._nickname;
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.playerId) {
			this._playerId = json.playerId;
		}
		if (json.serverId) {
			this._serverId = json.serverId;
		}
		if (json.nickname) {
			this._nickname = json.nickname;
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		byte.writeUint32(this._playerId);
		byte.writeLongNumber(this._serverId);
		byte.writeString(this._nickname);
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._playerId = byte.readUint32();
		this._serverId = byte.readLongNumber();
		this._nickname = byte.readString();
		return this;
	}


	/**克隆*/
	public clone(): Role {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = Role.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = Role.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//玩家id
			if (idx === E_Role.PLAYER_ID) {
				const oldv = this._playerId;
				this._playerId = us[i + 1];
				IAsync.dispatch(eventID, idx, this._playerId, oldv);
				i += 2;
				continue;
			}
			//服务器id
			if (idx === E_Role.SERVER_ID) {
				const oldv = this._serverId;
				this._serverId = us[i + 1];
				IAsync.dispatch(eventID, idx, this._serverId, oldv);
				i += 2;
				continue;
			}
			//昵称
			if (idx === E_Role.NICKNAME) {
				const oldv = this._nickname;
				this._nickname = us[i + 1];
				IAsync.dispatch(eventID, idx, this._nickname, oldv);
				i += 2;
				continue;
			}

			console.error('[Struct Data] can not find enum in Role with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: Role): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		if (this._playerId !== other._playerId) {
			updates.push(E_Role.PLAYER_ID, this._playerId);
		}
		if (this._serverId !== other._serverId) {
			updates.push(E_Role.SERVER_ID, this._serverId);
		}
		if (this._nickname !== other._nickname) {
			updates.push(E_Role.NICKNAME, this._nickname);
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(Role.TOTAL_EVENT_ID, this.getV(0));
	}

}
